package com.foreveross.weixin.service;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.foreveross.weixin.common.Constant;
import com.foreveross.weixin.util.WeixinUtil;
import com.foreveross.weixin.vo.AccessToken;
import com.foreveross.weixin.vo.JsApiTicket;

public class FrequencyService {
	private Logger log = Logger.getLogger(FrequencyService.class);
	
	private Timer timer = null; 
	
	//微信上频率为7200秒，为了失效内定频率accessToken为90分钟
	private final long accessTokenTimePeriod = 90*60*1000;
	//微信上频率为7200秒，为了失效内定频率jsApiTicket为105分钟
	private final long jsApiTicketTimePeriod = 105*60*1000;

	public Timer getTimer() {
		return timer;
	}
	
	public void setAccessToken(){
		timer = new Timer(); 	          
	    timer.schedule(getAccessTokenTask(),new Date(), accessTokenTimePeriod); 	    
	}
	
	public void setJsApiTicket(){
		timer = new Timer(); 	          
	    timer.schedule(getJsApiTicketTask(),new Date(), jsApiTicketTimePeriod); 	  
	}
	
	private TimerTask getAccessTokenTask(){
		return new TimerTask() {
	    	 public void run() {      
	    		//执行的内容   
	    		 getAccessToken();
	    	 }
	    };
	}
	
	private TimerTask getJsApiTicketTask(){
		return new TimerTask() {
	    	 public void run() {      
	    		//执行的内容   
	    		 getJsApiTicket();
	    	 }
	    };
	}
	
	/**
	 * 获取AccessToken
	 */
	private void getAccessToken(){
		log.info("获取AccessToken开始....");
		AccessToken accessToken;
		accessToken = WeixinUtil.getAccessToken(Constant.appId, Constant.appSecret);
		Constant.accessToken = accessToken;
		log.info("获取AccessToken结束....Constant.accessToken:"+Constant.accessToken.getAccess_token());
	}
	
	/**
	 * 获取JsApiTicket
	 */
	private void getJsApiTicket(){
		log.info("获取JsApiTicket开始....");
		int times = 0;
		if(Constant.accessToken == null) getAccessToken();
		while(Constant.accessToken == null && times<100){
			try {
				Thread.sleep(10*1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			times ++;
		}
		JsApiTicket jsApiTicket = WeixinUtil.getJsApiTicket(Constant.accessToken.getAccess_token());		

		Constant.jsApiTicket = jsApiTicket;
		log.info("获取JsApiTicket结束....Constant.jsApiTicket:"+Constant.jsApiTicket.getTicket());
	}
	
}
